import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Image, Platform, TouchableOpacity, TextInput, FlatList, PixelRatio
} from "react-native";
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { Common } from '../../../component/common/Common.js';
import { LargeBtn } from '../../requirement-plan/component/Component.js'

const scale = GLOBAL.SCALE;

let totalPage = 1;//总的页数

const requestObj = {
	pageSize: 10,
	status: '',
	userName: '',
};

const mask = require('../../../imgs/global/mask.png');
const optionPic = require('../../../imgs/global/option.png');
const optionCheckedPic = require('../../../imgs/global/success.png');
const searchLeft = require('../../../imgs/customer/searchLeft.png');
const searchRight = require('../../../imgs/global/inputDelete.png');
class SearchInput extends Component {
	constructor(props) {
		super(props);
		this.state = {
			opacity: 0,
			keyWord: ''
		}
	}

	componentDidMount () {
	}

	shouldComponentUpdate (nextProps, nextState) {
		//兼容0.54、0.55版本中iOS输入框不能输入中文
		if (Platform.OS === 'ios') {
			if (this.state.keyWord !== nextState.keyWord) { //keyWord为所要获得的TextInput输入值，
				return false;
			}
		}
		return true;
	};

	render () {
		return (
			<View style={styles.searchView}>
				<Image source={searchLeft} style={styles.searchLeftIcon} />
				<TextInput
					ref={"searchInput"}
					style={styles.searchInput}
					underlineColorAndroid='transparent'
					maxLength={20}
					placeholder='搜索'
					placeholderTextColor='#979797'
					value={this.state.keyWord}
					onChangeText={(txt) => {
						this.props.setKeyWord(txt);
						// this.props.doSearch();
						this.setState({ opacity: txt.length > 0 ? 1 : 0, keyWord: txt });
					}}
					onSubmitEditing={() => {
						this.props.doSearch();
					}}
				/>
				<TouchableOpacity onPress={() => {
					this.setState({
						opacity: 0,
						keyWord: ''
					});
					this.refs.searchInput.clear();
					this.props.setKeyWord('');
					this.props.doSearch();
				}} activeOpacity={0.5}>
					<Image source={searchRight} style={[styles.searchRightIcon, { opacity: this.state.opacity }]} />
				</TouchableOpacity>
			</View>
		);
	}

}


export class ReferenceListPage extends Component {

	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		return {
			headerTitle: <SearchInput setKeyWord={(txt) => { params.setKeyWord(txt); }} doSearch={() => { params.doSearch(); }} />,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} />,
			headerTintColor: style.color.dark,
			headerStyle: style.headTow.headerStyleWidthBorder,
			headerTitleStyle: style.headTow.headerTitleStyle,
			headerRight: (
				<Text style={{ marginRight: 10 * scale, fontSize: 12 * scale, color: '#404040' }} onPress={() => { params.doSearch(); }}>搜索</Text>
			),
		};
	};

	constructor(props) {
		super(props);
		this.state = {
			pageStatus: {
				status: 'loading'
			},
			isLoad: true,
			emptyResult: false,
			dataSource: [],
			userIdsChecked: {},
			userIdCheckedList: []
		}
		this._fetchStockInfo = this._fetchStockInfo.bind(this);
		this._renderItem = this._renderItem.bind(this);
		this._doSearch = this._doSearch.bind(this);
		this._setKeyWord = this._setKeyWord.bind(this);

		this.goBackPage = this.props.navigation.state.params.goBackPage;
		this.isSingle = this.props.navigation.state.params.isSingle;
		this.userIdCheckedList = this.props.navigation.state.params.usersFromStep1 || [];
		this.userIdsChecked = this.props.navigation.state.params.userIdsChecked;
		requestObj.userName = '';
		requestObj.pageNo = 1;

	}

	toggleUserIdChecked (item) {
		const { userIdsChecked, userIdCheckedList } = this.state;
		//userIdsChecked[item.userId]没有该项，则表示之前就没有选择过这个，也就说明这个item是点击选中状态，则直接push;
		if (userIdsChecked[item.userId]) {
			this.userIdCheckedList = this.userIdCheckedList.map((user, index) => {
				if (item.userId === user.staffId) {
					user['staffId'] = item.userId;
					user['staffName'] = item.userName;
					user['check'] = !user['check'];
					userIdsChecked[item.userId] = user;
				}
				return user;
			})
		} else {
			let newItem = {
				staffId: item.userId,
				staffName: item.userName,
				check: true
			}
			userIdsChecked[item.userId] = newItem;
			this.userIdCheckedList.push(newItem);
		}

		this.setState({
			userIdsChecked,
			userIdCheckedList: this.userIdCheckedList
		});
	}

	async _fetchStockInfo (pageNo, pageSize, onrefresh) {
		this.setState({
			loadIcon: true
		})

		const responseData = await HTTP.POST(API_GENERATE(API.GET_REFERENCR_LIST), {
			pageNo,
			userName: this.userName
		});

		totalPage = responseData.totalPage;

		this.setState({
			isLoad: false,
			loadIcon: false
		})

		if (responseData) {
			if (onrefresh) {  // 刷新
				this.setState({
					dataSource: responseData.rows
				})
			} else {  // 加载
				this.setState({
					dataSource: this.state.dataSource.concat(responseData.rows)
				})
			}
		}
	}

	async componentWillMount () {
		this.setState({
			userIdsChecked: this.userIdsChecked || {},
			userIdCheckedList: this.userIdCheckedList || {},
		});

		this.pageNo = 1;
		await this._fetchStockInfo(this.pageNo, true);

	}

	async componentDidMount () {
		this.props.navigation.setParams({
			doSearch: this._doSearch,
			setKeyWord: this._setKeyWord
		});
	}

	/**
 * 设置搜索关键字
 * @param {String} txt 
 */
	_setKeyWord (txt) {
		this.userName = txt;
	}
	_doSearch () {
		this.pageNo = 1;
		this.setState({
			isLoad: true,
			emptyResult: false,
			dataSource: [],
			// userIdsChecked: {},
		});
		this._fetchStockInfo(this.pageNo, true);
	}

	//状态-加载前
	_loadFn = () => {
		return (
			<View style={{ flex: 1 }}>
				<PageStatusIndex status="loading" />
			</View>
		)
	}

	//状态-获取到数据
	_bodyFn = () => {
		const { dataSource, userIdCheckedList } = this.state;
		const btnView = this.isSingle ? null : <LargeBtn text={'确定'} onPress={() => {
			const { navigate } = this.props.navigation;
			navigate(this.goBackPage, {
				users: userIdCheckedList,
			});
		}} />;

		return (
			<View style={styles.container}>
				{dataSource.length > 0 ? this._renderData() : <PageStatusIndex status="empty" emptyText="暂无记录" />}
				{btnView}
			</View >
		)
	}

	render () {
		let { isLoad } = this.state;
		if (isLoad) {
			return this._loadFn();
		} else {
			return this._bodyFn();
		}
	}

	/* 渲染列表 */
	_renderData () {
		const { dataSource } = this.state;
		return (
			<FlatList
				data={dataSource}
				renderItem={this._renderItem.bind(this)}
				onEndReachedThreshold={0.8}
				onEndReached={this._loadData.bind(this)}
				onRefresh={this._isLoadRefresh.bind(this)}
				refreshing={this.state.loadIcon}
			/>
		);
	}

	_renderItem (reference) {
		const { userIdsChecked } = this.state;
		const { avatarUrl, userName, organName, userId } = reference.item;
		const source = (avatarUrl && avatarUrl.length) ? { uri: avatarUrl } : mask;
		const optionSource = userIdsChecked[userId] && userIdsChecked[userId]['check'] ? optionCheckedPic : optionPic;

		if (this.isSingle) {
			return (
				<TouchableOpacity style={styles.row} activeOpacity={0.5} onPress={() => {
					const { navigate } = this.props.navigation;
					navigate(this.goBackPage, {
						user: reference.item,
					});
				}}>
					<View style={styles.rowLeft}>
						<Image source={source} style={styles.rowLeftPic} />
					</View>
					<View style={[styles.rowRight, { paddingLeft: 23 * scale, }]}>
						<Text style={styles.text}>{userName}</Text>
						<Text style={styles.text}>{organName}</Text>
					</View>
				</TouchableOpacity>
			)
		} else {
			return (
				<TouchableOpacity style={styles.row} activeOpacity={0.5} onPress={this.toggleUserIdChecked.bind(this, reference.item, reference.index)}>
					<View style={styles.rowLeft}>
						<Image source={source} style={styles.rowLeftPic} />
					</View>
					<View style={styles.rowRight}>
						<Text style={styles.text}>{userName}</Text>
						<Text style={styles.text}>{organName}</Text>
					</View>
					<View style={styles.rowLeft}>
						<Image source={optionSource} style={styles.optionPic} />
					</View>
				</TouchableOpacity>
			)
		}

	}

	// 下拉更新函数
	_isLoadRefresh () {
		this.pageNo = 1;
		this._fetchStockInfo(this.pageNo, true);
	}

	// 上拉加载
	_loadData () {
		if (totalPage > this.pageNo) {
			this.pageNo++;
			this._fetchStockInfo(this.pageNo, false);
		}
	}

}

const styles = StyleSheet.create({
	row: {
		flexDirection: 'row',
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
	},
	rowLeft: {
		width: 70 * scale,
		height: 72 * scale,
		justifyContent: 'center',
		alignItems: 'center',
	},
	optionPic: {
		height: 14 * scale,
		width: 14 * scale,
	},
	rowLeftPic: {
		height: 42 * scale,
		width: 42 * scale,
		borderRadius: 5,
	},
	rowRight: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
	},
	container: {
		flex: 1,
		backgroundColor: '#fff',
	},
	text: {
		fontSize: 14 * scale,
		color: '#4B4B4B'
	},
	footer: {
		flexDirection: 'row',
		height: 24,
		justifyContent: 'center',
		alignItems: 'center',
		marginBottom: 10,
	},
	noMoreText: {
		color: '#999999',
		fontSize: 14 * scale,
		marginTop: 5 * scale,
		marginBottom: 5 * scale,
	},
	searchView: {
		paddingLeft: 5 * scale,
		alignItems: 'center',
		flex: 1,
		flexDirection: 'row',
		width: 300 * scale,
		height: 31 * scale,
		backgroundColor: '#F6F6F6',
		borderRadius: 4,
	},
	searchInput: {
		padding: 0,
		flex: 1,
		height: 31 * scale,
		fontSize: 12 * scale,
		color: '#979797',
		marginLeft: 3 * scale,
	},
	searchLeftIcon: {
		height: 13 * scale,
		width: 13 * scale,
		marginLeft: 10 * scale,
		marginRight: 10 * scale,
	},
	searchRightIcon: {
		height: 10 * scale,
		width: 10 * scale,
		marginRight: 10 * scale,
	},
})